package com.web.transactionMonitor.service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.web.thread.GlobalThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.web.position.entity.Position;
import com.web.transaction.entity.Transaction;
import com.web.transactionMonitor.entity.TransactionMonitor;
import com.web.transactionMonitor.mapper.TransactionMonitorMapper;

@Service
public class TransactionMonitorService {

	@Autowired
    private TransactionMonitorMapper mapper;

	public List<TransactionMonitor> getTransactionMonitors(TransactionMonitor t){
		return mapper.getTransactionMonitors(t);
	}

	public TransactionMonitor getTransactionMonitor(String currency){
		return mapper.getTransactionMonitor(currency);
	}

	public int updateTransactionMonitor(TransactionMonitor t){
		return mapper.updateTransactionMonitor(t);
	}

	public int markAcknowledged(TransactionMonitor t){
		return mapper.markAcknowledged(t);
	}

	public int refreshLimitAmt(TransactionMonitor t){
		return mapper.refreshLimitAmt(t);
	}

	public void accumulate(List<Position> positions) {
		GlobalThreadPool.execute(() -> {
			for(Position p : positions) {
				TransactionMonitor t = getTransactionMonitor(p.getCurrency());
				if(p.getBuySellOption().equals(Transaction.TX_BUY)) {
					t.setBankBuyAmt(t.getBankBuyAmt().add(p.getAmount()));
				}else {
					t.setBankSellAmt(t.getBankSellAmt().add(p.getAmount()));
				}
				t.setNetAmt(t.getBankBuyAmt().subtract(t.getBankSellAmt()).abs());

				if(t.getNetAmt().subtract(t.getLimitAmt()).compareTo(BigDecimal.ZERO) >=0) {
					//TODO 超过限额，需提醒
					t.setReachedDateTime(LocalDateTime.now());
					t.setAcknowledged("N");
				}

				updateTransactionMonitor(t);
			}
		});
	}
}
